package com.ruifu.proj.service.impl;

import com.fhzncloud.cloud.common.security.service.CloudUser;
import com.ruifu.common.po.PmPhaseTask;
import com.ruifu.common.po.PmPtMain;
import com.ruifu.common.utils.BeanConverter;
import com.ruifu.proj.dto.phasetask.PmPhaseTaskDTO;
import com.ruifu.proj.mapper.PmPhaseTaskMapper;
import com.ruifu.proj.mapper.PmPtMainMapper;
import com.ruifu.proj.service.PmPhaseTaskService;
import com.ruifu.proj.vo.phasetask.PmPhaseTaskVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author nyr
 * @create 2019/9/18
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class PmPhaseTaskServiceImpl implements PmPhaseTaskService {
    @Autowired(required = false)
    private PmPhaseTaskMapper pmPhaseTaskMapper;

    @Autowired(required = false)
    private PmPtMainMapper pmPtMainMapper;

    @Override
    public List<PmPhaseTaskVO> findByPpPtid(Long ptId) {
        /*查询该项目的配置列表*/
        List<PmPhaseTask> phaseTaskList = pmPhaseTaskMapper.findByPpPtId(ptId);
        //判断是否为空或者长度为0
        if (phaseTaskList == null || phaseTaskList.size() == 0) {
            /*根据项目id查询项目*/
            PmPtMain pmPtMain = pmPtMainMapper.findById(ptId);
            //获取项目类型阶段定义
            String pyPhase = pmPtMain.getPmPType().getPyPhase();
            //切割阶段定义
            String[] ppPhaseNames = pyPhase.split(";");
            //遍历
            for (String ppPhaseName : ppPhaseNames) {
                PmPhaseTask pmPhaseTask = new PmPhaseTask();
                pmPhaseTask.setPpPhaseName(ppPhaseName);
                phaseTaskList.add(pmPhaseTask);
            }
        }
        /*PO转VO*/
        return BeanConverter.copyList(phaseTaskList, PmPhaseTaskVO.class);
    }

    @Override
    public void save(List<PmPhaseTaskDTO> phaseTaskDTOList, CloudUser cloudUser) {
        //非空校验
        if (phaseTaskDTOList == null || phaseTaskDTOList.size() == 0) {
            throw new RuntimeException("配置集合不存在");
        }
        for (PmPhaseTaskDTO pmPhaseTaskDTO : phaseTaskDTOList) {
            //判断是否包含了主键
            if (pmPhaseTaskDTO.getPpId() == null) {
                /*DTO转PO*/
                PmPhaseTask pmPhaseTask = BeanConverter.copyProperties(pmPhaseTaskDTO, PmPhaseTask.class);
                //设置帐套id
                pmPhaseTask.setPpSetSid(Long.valueOf(cloudUser.getTenantId()));
                /*新建配置*/
                pmPhaseTaskMapper.insert(pmPhaseTask);
            } else {
                /*修改配置*/
                //根据id查询数据
                PmPhaseTask pmPhaseTask = pmPhaseTaskMapper.findById(pmPhaseTaskDTO.getPpId());
                /*DTO合并PO*/
                BeanConverter.copyProperties(pmPhaseTaskDTO, pmPhaseTask);
                pmPhaseTaskMapper.update(pmPhaseTask);
            }
        }
    }
}
